/*
 * typeListener 1.0 - Plugin for jQuery
 * 
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Depends:
 *   jquery.js
 *	 
 *
 *  Copyright (c) 2008 Oleg Slobodskoi (ajaxsoft.de)
 */

;(function($) {

	$.fn.extend({
		typeListener: function(options, callback) {

			if ($.isFunction(options) || typeof options == 'string')
			{
				callback = options;
				options = null;
			};
			if (!callback)	
				callback = function(){};

			return this.each(function() {
				new $.typeListener(this, options, callback);
			});
		}
	});


	$.typeListener = function(elem, options, callback)
	{
	
		var d = {
			wait: 1000,
			enterWatch: true,
			escapeWatch: true,
			start: null,
			abort: null,
			abortHandle: null
		};
		
		$.extend(d, options);
		
		var timeout, running = false, $abortHandle;
		
		$abortHandle = (typeof d.abortHandle == 'string') ? $(d.abortHandle) : d.abortHandle;
		$abortHandle && $abortHandle.click(abort);		
	
		$(elem).keydown(function (e){
			clearTimeout(timeout);

			if ( d.start && !running )
			{
				running = true;
				createCallback(d.start,[elem, $abortHandle]);
			};

			if (d.enterWatch && e.keyCode == 13)
				runCallback();
			else if (d.escapeWatch && e.keyCode == 27)
				abort();
			else
				timeout = setTimeout(runCallback,d.wait);
		});
		

		function abort ()
		{
			running = false;
			createCallback(d.abort, [elem, $abortHandle]);			
		};
		
		function runCallback ()
		{
			createCallback(callback,[$(elem).val(), elem]);
		};
		
		function createCallback (f,params)
		{		
			typeof f == 'string' && eval('f='+f);
			$.isFunction(f) && f.apply(f,params);
		};			
		

	};


	
})(jQuery);
